package com.hdu.transmitableThreadLocal;

import java.util.HashMap;
import java.util.Map;

public class TransmitableRunnable implements Runnable {

    private final Runnable ORIGINAL;
    @SuppressWarnings("all")
    private final Map<TransmitableThreadLocal, Object> CONTEXT;


    public static TransmitableRunnable wrap(Runnable original) {
        return new TransmitableRunnable(original);
    }


    private TransmitableRunnable(Runnable ORIGINAL) {
        this.ORIGINAL = ORIGINAL;
        CONTEXT = new HashMap<>();
        // 抓取当前线程的所有 TransmitableThreadLocal
        CONTEXT.putAll(TransmitableThreadLocalHolder.get());
    }

    @Override
    public void run() {
        // 回放 父线程的所有 TransmitableThreadLocal
        CONTEXT.forEach(
                TransmitableThreadLocal::set
        );
        // 执行原始的 Runnable逻辑
        ORIGINAL.run();
    }
}
